﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace Gum.FizzBuzz
{
    public class FizzBuzzJobFactory : IFizzBuzzJobFactory
    {
        public IFizzBuzzJob Create(int start, int end, IEnumerable<KeyValuePair<int, string>> mappings)
        {
            var job = new FizzBuzzJob(start, end);

            job.TransformFunction = CreateTransformFunction(mappings);
            return job;
        }

        private Func<int, string> CreateTransformFunction(IEnumerable<KeyValuePair<int, string>> mappings)
        {
            return input =>
                       {
                           var stringBuilder = new StringBuilder();
                           foreach (var mapping in mappings)
                           {
                               if (input % mapping.Key == 0) stringBuilder.Append(mapping.Value);
                           }
                           var result = stringBuilder.ToString();
                           return String.IsNullOrEmpty(result) ? 
                               input.ToString(CultureInfo.InvariantCulture) : 
                               stringBuilder.ToString();
                       };
        }
    }
}